import { constantRouterMap } from '@/router/routers'
import Layout from '@/layout/index'
import ParentView from '@/components/ParentView'

const permission = {
  state: {
    routers: constantRouterMap,
    addRouters: [],
    sidebarRouters: [],
    permissions: []
  },
  mutations: {
    SET_ROUTERS: (state, routers) => {
      state.addRouters = routers
      state.routers = constantRouterMap.concat(routers)
    },
    SET_SIDEBAR_ROUTERS: (state, routers) => {
      state.sidebarRouters = constantRouterMap.concat(routers)
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions
    }
  },
  actions: {
    GenerateRoutes({ commit }, asyncRouter) {
      commit('SET_ROUTERS', asyncRouter)
    },
    SetSidebarRouters({ commit }, sidebarRouter) {
      commit('SET_SIDEBAR_ROUTERS', sidebarRouter)
    },
    SetUserPermission({ commit }, permissions) {
      commit('SET_PERMISSIONS', permissions)
    },
    DeletePermission({ state, commit }, permission) {
      state.permissions = state.permissions.filter(item => item !== permission)
    }
  }
}

export const filterAsyncRouter = (routers, lastRouter = false, type = false) => { // 遍历后台传来的路由字符串，转换为组件对象
  return routers.filter(router => {
    if (type && router.children) {
      router.children = filterChildren(router.children)
    }
    if (router.component) {
      if (router.component === 'Layout') { // Layout组件特殊处理
        router.component = Layout
      } else if (router.component === 'ParentView') {
        router.component = ParentView
      } else {
        const component = router.component
        router.component = loadView(component)
      }
    }
    if (router.children != null && router.children && router.children.length) {
      router.children = filterAsyncRouter(router.children, router, type)
    } else {
      delete router['children']
      delete router['redirect']
    }
    return true
  })
}

function filterChildren(childrenMap, lastRouter = false) {
  var children = []
  childrenMap.forEach((el, index) => {
    if (el.children && el.children.length) {
      if (el.component === 'ParentView') {
        el.children.forEach(c => {
          c.path = el.path + '/' + c.path
          console.log(c.path)

        })
        if (el.children && el.children.length) {
          children = children.concat(filterChildren(el.children, el))
          return
        }

      }
    }

    children = children.concat(el)
  })
  return children
}

export const loadView = (view) => {
  return (resolve) => require([`@/views/${view}`], resolve)
}

/**
 * 添加动态(菜单)路由
 * @param {*} menuList 菜单列表
 * @param {*} routes 递归创建的动态(菜单)路由
 */
export function fnAddDynamicMenuRoutes(menuList) {
  const temp_routers = []

  for (let i = 0; i < menuList.length; i++) {
    if (!menuList[i].url && (!menuList[i].list || menuList[i].list.length === 0)) continue

    let temp_router = {
      'hidden': menuList[i].hidden,
      'name': menuList[i].name,
      'meta': {
        'icon': menuList[i].icon,
        'noCache': true,
        'title': menuList[i].name,
        'menuId': menuList[i].menuId + ''
      },
      'path': menuList[i].url ? menuList[i].url : '/'
    }

    if (menuList[i].parentId === 0 ) {
      temp_router.component='Layout';

      //如果是一级目录并且没有子菜单
      if(!menuList[i].list || !menuList[i].list.length){
        temp_router.children=[];
        temp_router.meta=null;
        delete temp_router.name
        let sub_router = {
          'hidden': menuList[i].hidden,
          'name': menuList[i].name,
          'meta': {
            'icon': menuList[i].icon,
            'title': menuList[i].name,
            'menuId': menuList[i].menuId + ''
          },
          'component':menuList[i].component?menuList[i].component:null,
          'path': ''
        }
        temp_router.children.push(sub_router)
      }

    } else {
      // 如果不是一级菜单，并且菜单类型为目录，则代表是多级菜单
      if(menuList[i].type===0){
        temp_router.component='ParentView'
      }else{
        if (menuList[i].component) {
          temp_router.component = menuList[i].component
        } else {
          continue
        }
      }

    }
    if (menuList[i].list && menuList[i].list.length) {
      temp_router.redirect = 'noredirect'
      temp_router.alwaysShow = true
      temp_router.children = fnAddDynamicMenuRoutes(menuList[i].list)
    }
    // console.log(temp_router)
    temp_routers.push(temp_router)
  }

  return temp_routers
}

export default permission
